﻿using Face8280WebSocketServer.DB.People;
using Face8280WebSocketServer.DB.System;
using Face8280WebSocketServer.Interface;
using Face8280WebSocketServer.Utility;
using Face8280WebSocketServer.Utility.ExpressionExtend;
using Face8280WebSocketServer.Utility.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Service
{
    public class FacePeopleService : BaseService, IFacePeopleService
    {
        public FacePeopleService(DbContext context) : base(context)
        {
        }
        public FacePeopleInfo GetPeopleById(int id)
        {
            return Find<FacePeopleInfo>(id);
        }
        public FacePeopleInfo GetPeopleByCode(uint code)
        {
            return Set<FacePeopleInfo>().FirstOrDefault(x => x.Code == code);
        }
        public JsonResultModel Add(DB.People.FacePeopleInfo peopleInfo)
        {
            #region 重复过滤
            Expression<Func<FacePeopleInfo, bool>> oWheres = null;
            if (peopleInfo.Code > 0) oWheres = x => x.Code.Equals(peopleInfo.Code);
            if (peopleInfo.Card > 0) oWheres = oWheres.Or(x => x.Card.Equals(peopleInfo.Card));

            var peopleQuery = Query<FacePeopleInfo>(oWheres).AsNoTracking();
            var peoples = from p in peopleQuery
                          select new
                          {
                              p.Id,
                              p.Code,
                              p.Card,
                              p.Name
                          };


            if (peoples.Count() > 0)
            {
                foreach (var p in peoples)
                {
                    if (peopleInfo.Code > 0 && p.Code == peopleInfo.Code)
                    {
                        return new JsonResultModel(200, $"人员编号重复，重复人员名称：{p.Name}");
                    }
                    if (peopleInfo.Card > 0 && p.Card == peopleInfo.Card)
                    {
                        new JsonResultModel(201, $"人员卡号重复，重复人员名称：{p.Name}({p.Code})");
                    }
                }

            }
            #endregion

            if (peopleInfo.Code == 0)
            {
                peopleInfo.Code = GetNewAutoEmployeeID();
            }
            if (peopleInfo.PhotoData != null)
                peopleInfo.Photo = FileIOUtility.WriteFaceImage(peopleInfo.Code, peopleInfo.PhotoData);
            AddUserLog("人员管理",
                $"添加人员：{peopleInfo.Name}({peopleInfo.Code}),职务：{peopleInfo.Job},卡号：{peopleInfo.Card},照片地址：{peopleInfo.Phone}",
                string.Empty, $"{peopleInfo.Name}({peopleInfo.Code})");
            Insert(peopleInfo);

            return new JsonResultModel();
        }

        public JsonResultModel Update(FacePeopleInfo peopleInfo)
        {
        //    Console.WriteLine("11111");
            var table = Set<FacePeopleInfo>();
            var people = table.AsNoTracking().FirstOrDefault(a => a.Id == peopleInfo.Id);
            if (people == null) return new JsonResultModel(101, "人员不存在");
            if (peopleInfo.PhotoData == null && string.IsNullOrWhiteSpace(peopleInfo.Photo))
            {
                var sFile = GetImageFileName(people.Photo);
                if (System.IO.File.Exists(sFile))
                    System.IO.File.Delete(sFile);
            }
            else
            {
                if (peopleInfo.PhotoData != null)
                    peopleInfo.Photo = FileIOUtility.WriteFaceImage(people.Code, peopleInfo.PhotoData);
            }
            base.Update(peopleInfo);
            return new JsonResultModel("更新成功");

        }

        public JsonResultModel Delete(HashSet<int> peopleIDLists)
        {
            var peoplesDB = Query<FacePeopleInfo>(x => peopleIDLists.Contains(x.Id));
            foreach (var p in peoplesDB)
            {
                AddUserLog("人员管理",
            $"删除人员：{p.Name}({p.Code}),职务：{p.Job},卡号：{p.Card},照片地址：{p.Photo}",
            string.Empty, $"{p.Name}({p.Code})");
                if (!string.IsNullOrWhiteSpace(p.Photo))
                {
                    var sFileName = GetImageFileName(p.Photo);
                    if (System.IO.File.Exists(sFileName))
                    {
                        try
                        {
                            System.IO.File.Delete(sFileName);
                        }
                        catch
                        { }
                    }
                }
            }
            base.Delete(peoplesDB.AsEnumerable());
            return new JsonResultModel();
        }
        public uint GetNewAutoEmployeeID()
        {

            //需要自动分配一个ID；
            var sysdb = GetSystemKVDBSet();
            var kv = sysdb.Find("AutoEmployeeID");
            uint iAutoEmployeeID = 10000;
            if (kv == null)
            {

                kv = new() { Key = "AutoEmployeeID", Value = "10000" };
                Insert<SystemKV>(kv);
            }
            else
            {

                iAutoEmployeeID = uint.Parse(kv.Value);
            }

            var EmplIDs = new HashSet<uint>(Query<FacePeopleInfo>(null).Select(p => p.Code));
            do
            {
                if (!EmplIDs.Contains(iAutoEmployeeID))
                {
                    break;
                }
                iAutoEmployeeID++;
            } while (true);


            kv.LastUpdateTime = DateTime.Now;
            kv.Value = iAutoEmployeeID.ToString();
            Update(kv);
            return iAutoEmployeeID;

        }

        /// <summary>
        /// 从URL 连接中获取文件名，去掉末尾的?crc
        /// </summary>
        /// <param name="sPath"></param>
        /// <param name="sFileName"></param>
        /// <returns></returns>
        private string GetImageFileName(string sURL)
        {
            string sPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");


            var iIndex = sURL.LastIndexOf("?");
            if (iIndex > 0)
            {
                sURL = sURL.Substring(0, iIndex);
            }
            string[] sURLSegments = sURL.Split("/");
            string sFile = sPath;
            foreach (var sSegment in sURLSegments)
            {
                sFile = Path.Combine(sFile, sSegment);
            }
            return sFile;
        }
    }
}
